local p = {}
-- 通用
local getArgs = require('Module:Arguments').getArgs
local inArray = require('Module:Util').inArray
local OrderedTable = require('Module:OrderedTable')
local WEAPON_MAP = require('Module:Util/Config').WEAPON_MAP
local weapon_info_map = require('Module:Util/Weapon')

---------------------------------------------------------------------------
-- 常量
---------------------------------------------------------------------------

local WEAPON_LIST = {'1', '2', '3', '4', '5', '6'}

---------------------------------------------------------------------------
-- 获取数据
---------------------------------------------------------------------------

function p.query_data(rarity)
	-- 按武器类型整理数据
	local output = {}
	for _, type in ipairs(WEAPON_LIST) do
		output[type] = {}
	end

	for _, card_info in pairs(weapon_info_map) do
	    card_info.ID = _
		if (tonumber(card_info.ID) or 0) > 0 and (card_info.addDate or '') ~= '' then
		    if (rarity or '') == '' or (card_info.rarity == rarity) then
				table.insert(output[card_info.weaponType], card_info)
			end
		end
	end
	
	for _, type in ipairs(WEAPON_LIST) do
		table.sort(output[type], p.sort_weapon_data)
	end
	
	return output
end

function p.sort_weapon_data(a, b)
    if (a.addDate ~= b.addDate) then
		return a.addDate < b.addDate
	else
		return a.ID < b.ID
	end
end

function p.reverseTable(tab)
	local tmp = {}
	for i = 1, #tab do
		local key = #tab
		tmp[i] = table.remove(tab)
	end

	return tmp
end

-----------------------------------------------------------------------------
-- 武器信息页生成
-----------------------------------------------------------------------------

function p.weapon_list(frame)
	local args = getArgs(frame)

	local rarity = args[1] or ''
	local picture_l = picture
	local bool = true
	local weapon_data = p.query_data(rarity)

	local html = mw.html.create()
	for _, type in ipairs(WEAPON_LIST) do
		if #weapon_data[type] > 0 then
			local type_name = WEAPON_MAP[type]

			local h2 = html:tag('h2'):cssText('font-size:24px;'):wikitext('[[File:CharWeapon_'..type..'.png|25px]]'..type_name)

			local flex_list = html:tag('div'):addClass('flex-list m-flex-list'):cssText('text-align: center;font-size:14px;')
	
			for _, card_info in ipairs(weapon_data[type]) do
				local link = 'Weapon/'..card_info.ID
				flex_list:tag('div'):addClass('flex-item summon-box'):tag('div'):addClass('image'):wikitext('[[File:s_'..card_info.ID..'.png|link='..link..']]'):done()
				:tag('div'):addClass('text'):wikitext('[['..link..'|'..(card_info.tag_title or card_info.name)..']]'):done()
			end
		end
	end

	return html

	-- body
end


return p
